﻿using System.Threading.Tasks;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Model.Tokens;
using Model.View;
using Utils.UserHelper;

namespace ViewModel.WindowViewModel;

public partial class LoginViewModel : ObservableObject
{
    #region ViewModel

    [ObservableProperty] private string? _account;
    [ObservableProperty] private string? _password = "";
    [ObservableProperty] private bool _memory;
    [ObservableProperty] private Visibility _message = Visibility.Hidden;
    [ObservableProperty] private bool _loginSuccess = true;
    [ObservableProperty] private bool _logoutSuccess = false;

    #endregion

    [RelayCommand]
    private async Task Login(string pwd)
    {
        var res = await UserLogin.Login(new ViewUser
        {
            Account = Account,
            Password = pwd,
            Memory = Memory
        });
        if (res)
        {
            LoginSuccess = false;
            LogoutSuccess = true;
            Message = Visibility.Hidden;
            WeakReferenceMessenger.Default.Send(new MainContentTokenModel() { Token = "Main" });
        }
        else
        {
            Message = Visibility.Visible;
        }
        
    }

    [RelayCommand]
    private async Task Logout()
    {
        LoginSuccess = true;
        LogoutSuccess = false;
        UserLogin.LoginUser = null;
    }

    public LoginViewModel()
    {
        Task.Run(async () => { await Initializetion(); });
    }

    private async Task Initializetion()
    {
        var res = await FindMemoryUser.FindHistoryMemoryUser();
        if (res == null)
            return;
        Account = res.Account;
        Password = res.Password;
        Memory = res.Memory;
    }
}